import type{Router} from "vue-router"
import {auth as useAuth,user as useUser} from  "@/store"
import {isLogin,getToken} from "@/common/utils"
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import {ElMessage as message } from "element-plus";
import {authRouteMode} from "@/common/config"


nprogress.configure({
  // 动画方式
  easing: "ease",
  // 递增进度条的速度
  speed: 500,
  // 是否显示加载ico
  showSpinner: false,
  // 自动递增间隔
  trickleSpeed: 200,
  // 初始化时的最小百分比
  minimum: 0.3,
});


const nologin=["/login"]


export default(router:Router)=>{
  router.beforeEach(async(to,from,next)=>{
    //console.log(router.getRoutes())
    //console.log(to.name,to.fullPath)
    nprogress.start()
    if(authRouteMode=='local')  {next();return}
    if(nologin.some(v=>(to.fullPath.includes(v)))) next()  
    else {
       if(isLogin()) {
        const auth=useAuth()
        // 判断是否有 accessedRoutes
        if(auth.routeConfig.length)
        next()
        else{
        let res
          res= await auth.setAuth(getToken())
         if(res.code==201) {  // token失效
          next(false)
          const user=useUser()
          user.logout(from.fullPath)
          message.warning('登录信息失效，请重新登录')
          return
        }
         if(res.code==200)  {
          res.accessedRoutes.forEach((v:any)=>router.addRoute(v)) 
          next(to.fullPath)
         }
         else {  // 可能是网络问题或者服务器问题
          message.error('获取角色信息失败，请重新登录或者刷新获取')
          res.accessedRoutes.forEach((v:any)=>router.addRoute(v))
          next('/')
          
         }
         console.log('accessedRoutes',res.accessedRoutes)
         // console.log('accessedRoutes',router.getRoutes())
        }
       }
       else {
        const redirect=from.fullPath.includes("/login")?"":from.fullPath
        if(redirect)
        next({path:'/login',query:{redirect:encodeURIComponent(redirect)},replace:true})
        else {
          next(false)
          nprogress.done()
        }
       }
    }
  })
  
  router.afterEach((to,_from)=>{
     document.title=`${to.meta.title} - vue3后台系统模板`
     nprogress.done()
  })
}

